package com.xiaoyu.izf.controller.api;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.xiaoyu.izf.config.MyConfig;
import com.xiaoyu.izf.config.SysConfig;
import com.xiaoyu.izf.model.GoodsOrder;
import com.xiaoyu.izf.model.OrderInfo;
import com.xiaoyu.izf.model.UserInfo;
import com.xiaoyu.izf.model.VipOrder;
import com.xiaoyu.izf.model.page.FormResult;
import com.xiaoyu.izf.service.GoodsOrderService;
import com.xiaoyu.izf.service.OrderInfoService;
import com.xiaoyu.izf.service.UserInfoService;
import com.xiaoyu.izf.service.VipOrderService;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("/api/order")
public class OrderApiController extends BaseApiController{
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private MyConfig myConfig;
    @Autowired
    private VipOrderService vipOrderService;
    @Autowired
    private GoodsOrderService goodsOrderService;
    @Autowired
    private UserInfoService userInfoService;

    /**
     *
     * @param req
     * @param orderId
     * @param orderType  1:vip  2:商品
     * @return
     */
    @RequestMapping("/alipay")
    @ResponseBody
    public FormResult<String> orderAlipayGet(HttpServletRequest req, String orderId, int orderType){
        FormResult<String> fr = new FormResult<>();
        String clientIp = getip(req);
        int totAmount = 0;
        VipOrder vipOrder = null;
        GoodsOrder goodsOrder = null;
        UserInfo userInfo = null;
        String body = "";
        if(orderType==1){
            vipOrder = vipOrderService.vipOrder(orderId);
            totAmount = vipOrder.getTotAmount();
            userInfo = userInfoService.userInfo(vipOrder.getUid());
            body = "VIP购买";
        }
        if(orderType==2){
            goodsOrder = goodsOrderService.orderOne(orderId);
            totAmount = goodsOrder.getTotalAmount();
            userInfo = userInfoService.userInfo(goodsOrder.getUid());
            body = "商品购买";
        }
        if(vipOrder==null&&goodsOrder==null){
            fr.setStatus(404);
            fr.setMessage("订单不存在。");
            return fr;
        }
        if(SysConfig.isTestPrice==1||userInfo.getIsTest()==1){
            totAmount = 1;
        }
        DecimalFormat df=new DecimalFormat("0.00");
        String totAmountFloat = df.format(totAmount/(float)100);
        String outtradeno = "d"+System.currentTimeMillis() + (long) (Math.random() * 10000000L);
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", SysConfig.aliPayAppId, SysConfig.aliPayAppPivateKey, "json", "UTF-8", SysConfig.aliPayPublicKey, "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        String redirect_uri = myConfig.getHost()+"api/order/tradeCreateNotifyAlipay";
        model.setBody(body);
        model.setSubject("商品购买");
        model.setOutTradeNo(outtradeno);
        model.setTimeoutExpress("30m");
        model.setTotalAmount(totAmountFloat);
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(redirect_uri);
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
            if(orderType==1){
                orderInfoService.vipOrderAdd(outtradeno,vipOrder,clientIp,totAmount,userInfo.getIsTest());
            }
            if(orderType==2){
                orderInfoService.goodsOrderAdd(outtradeno,goodsOrder,clientIp,totAmount,userInfo.getIsTest());
            }
            fr.setData(response.getBody());
            fr.setStatus(200);
            fr.setMessage("ok");
            return fr;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        fr.setStatus(404);
        fr.setMessage("未知错误。");
        return  fr;
    }

    @RequestMapping("/tradeCreateNotifyAlipay")
    @ResponseBody
    public String tradeCreateNotifyAlipay(HttpServletRequest request, HttpServletResponse response) throws Exception{
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
            System.out.println("name:"+name+"===value:"+valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean flag = AlipaySignature.rsaCheckV1(params, SysConfig.aliPayPublicKey, "UTF-8","RSA2");
        if(flag){
            String outTradeNo = params.get("out_trade_no");
            String tradeStatus = params.get("trade_status");
            if("TRADE_SUCCESS".equals(tradeStatus)) {
                OrderInfo order = orderInfoService.orderInfo(outTradeNo);
                if (order.getOrderStatus() == 0) {
                    orderInfoService.orderPay(outTradeNo);
                }
            }
            return "success";
        }
        return "fail";
    }
}
